// 文件路径: src/main/java/com/example/demo22/controller/AuthController.java

package com.example.demo22.controller;

import com.example.demo22.dto.UserDTO;
import com.example.demo22.entity.User;
import com.example.demo22.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Slf4j
@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public ModelAndView openHomePage(HttpSession session, ModelAndView mv) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            mv.setViewName("index");
            mv.addObject("username", user.getUsername());
        } else {
            mv.setViewName("login");
        }
        return mv;
    }

    @GetMapping("/login")
    public String openLoginPage() {
        return "login";
    }

    @PostMapping("/login")
    public ModelAndView login(UserDTO userDTO, ModelAndView mv, HttpSession session, HttpServletRequest request) {
        log.info("登录请求: {}", userDTO);
        try {
            User user = userService.login(userDTO);
            if (user != null) {
                session.setAttribute("user", user);
                mv.setViewName("redirect:/index");
                mv.addObject("username", user.getUsername());
                log.info("用户 {} 登录成功，IP: {}", user.getUsername(), request.getRemoteAddr());
            } else {
                mv.addObject("msg", "用户名或密码错误");
                mv.setViewName("login");
            }
        } catch (Exception e) {
            log.error("登录失败: ", e);
            mv.addObject("msg", "登录失败，请重试");
            mv.setViewName("login");
        }
        return mv;
    }

    @GetMapping("/deleteAccount")
    public String showDeleteConfirmationPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("username", user.getUsername());
        return "deleteAccount";
    }

    @PostMapping("/deleteAccount")
    public ModelAndView handleDeleteAccount(
            @RequestParam("username") String inputUsername,
            HttpSession session,
            ModelAndView mv) {

        User user = (User) session.getAttribute("user");

        if (user == null) {
            mv.setViewName("redirect:/login");
            mv.addObject("msg", "请先登录");
            return mv;
        }

        if (!user.getUsername().trim().equalsIgnoreCase(inputUsername.trim())) {
            mv.setViewName("deleteAccount");
            mv.addObject("errorMsg", "用户名不正确，无法注销");
            mv.addObject("username", user.getUsername());
            return mv;
        }

        try {
            userService.deleteUserById(user.getId());
            session.invalidate();
            mv.setViewName("deleteSuccess");
            mv.addObject("msg", "您的账号已成功注销");
        } catch (Exception e) {
            log.error("注销失败：", e);
            mv.setViewName("redirect:/index");
            mv.addObject("msg", "注销失败，请稍后再试");
        }

        return mv;
    }

    @GetMapping("/register")
    public String openRegisterPage() {
        return "register";
    }

    @PostMapping("/register")
    public ModelAndView register(UserDTO userDTO, ModelAndView mv) {
        log.info("注册请求: {}", userDTO);
        try {
            userService.register(userDTO);
            mv.setViewName("redirect:/login");
            mv.addObject("msg", "注册成功，请登录");
        } catch (Exception e) {
            log.error("注册失败: ", e);
            mv.addObject("msg", "注册失败：" + e.getMessage());
            mv.setViewName("register");
        }
        return mv;
    }

    @GetMapping("/forgotPassword")
    public String openForgotPasswordPage() {
        return "forgotPassword";
    }

    @PostMapping("/forgotPassword")
    public ModelAndView handleForgotPassword(@RequestParam("username") String username,
                                             @RequestParam("email") String email,
                                             @RequestParam("newPassword") String newPassword,
                                             ModelAndView mv, HttpSession session) {
        log.info("忘记密码请求: 用户名={}, 邮箱={}", username, email);

        try {
            User user = userService.findByUsername(username);
            if (user == null) {
                mv.addObject("msg", "用户名不存在");
                mv.setViewName("forgotPassword");
                return mv;
            }

            if (!user.getEmail().equals(email)) {
                mv.addObject("msg", "邮箱不匹配");
                mv.setViewName("forgotPassword");
                return mv;
            }

            userService.updatePassword(user.getId(), newPassword);
            mv.setViewName("redirect:/login");
            mv.addObject("msg", "密码修改成功，请登录");
        } catch (Exception e) {
            log.error("修改密码失败: ", e);
            mv.addObject("msg", "密码修改失败：" + e.getMessage());
            mv.setViewName("forgotPassword");
        }

        return mv;
    }

    @GetMapping("/userList")
    public String userList(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return "redirect:/login";
        }

        List<User> userList = userService.findAllUsers();
        model.addAttribute("userList", userList);
        model.addAttribute("totalLogins", userService.countTotalLogins());
        model.addAttribute("todayLogins", userService.countTodayLogins());
        return "userList";
    }

    @GetMapping("/profile")
    public String profile(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/updateProfile")
    public ModelAndView updateProfile(User user, HttpSession session, ModelAndView mv) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            mv.setViewName("redirect:/login");
            return mv;
        }

        currentUser.setUsername(user.getUsername());
        currentUser.setEmail(user.getEmail());
        currentUser.setSex(user.getSex());

        try {
            userService.updateUserInfo(currentUser);
            session.setAttribute("user", currentUser);
            mv.setViewName("redirect:/profile");
            mv.addObject("msg", "个人资料更新成功");
        } catch (Exception e) {
            log.error("更新个人资料失败: ", e);
            mv.addObject("msg", "资料更新失败：" + e.getMessage());
            mv.addObject("user", currentUser);
            mv.setViewName("profile");
        }

        return mv;
    }

    @GetMapping("/changePassword")
    public String changePasswordPage(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        return "changePassword";
    }

    @PostMapping("/changePassword")
    public ModelAndView changePassword(@RequestParam("oldPassword") String oldPassword,
                                       @RequestParam("newPassword") String newPassword,
                                       HttpSession session, ModelAndView mv) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            mv.setViewName("redirect:/login");
            return mv;
        }

        if (!currentUser.getPassword().equals(oldPassword)) {
            mv.addObject("msg", "旧密码不正确");
            mv.setViewName("changePassword");
            return mv;
        }

        try {
            userService.updatePassword(currentUser.getId(), newPassword);
            currentUser.setPassword(newPassword);
            session.setAttribute("user", currentUser);
            mv.setViewName("redirect:/profile");
            mv.addObject("msg", "密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败: ", e);
            mv.addObject("msg", "密码修改失败：" + e.getMessage());
            mv.setViewName("changePassword");
        }

        return mv;
    }
}
